﻿using il2lua.Services;

using Mono.Cecil;
namespace il2lua;

public class ModuleContext
{
    private readonly Dictionary<string, ILuaRole> _roles;
    private readonly Dictionary<string, int> _renameCount;
    private INameService _nameCreation;
    public ModuleContext()
    {
        _nameCreation = Services.Services.GetService<INameService>();
        _roles = new Dictionary<string, ILuaRole>();
        _renameCount = new Dictionary<string, int>();
    }
        
    private ILuaRole CreateRole(string name, string space)
    {
        return new LuaRole( name, space);
    }
        
    public ILuaRole GetRole(TypeReference type)
    {
        var key = type.FullName;
        if (_roles.TryGetValue(key, out var role))
            return role;
        var typeDef = type.Resolve();
        if (typeDef != null)
            return GetRole(typeDef);
        return _roles[key] = CreateRole(_nameCreation.GetName(type.Name), type.Namespace);
    }
        
    public ILuaRole GetRole(TypeDefinition type)
    {
        var key = type.FullName;
        if (_roles.TryGetValue(key, out var role))
            return role;
        return _roles[key] = CreateRole(_nameCreation.GetName(type.Name), type.Namespace);
    }

}